#include "cfilecalendar.h"

#include "ccalmanager.h"
#include "sql_bind.h"

#include <buola/io/cfile.h>

namespace buola { namespace bcal {

CFileCalendar::CFileCalendar(CCalManager *pManager,int pID)
    :   mManager(pManager)
//    ,   mID(pID)
{
    CDBQuery *lQ=&mManager->mQueries.mGetCalendar;
    lQ->BindInteger(BIND_GETCALENDAR_ID,pID);

    lQ->Exec();
    
    if(!lQ->NextRow())
    {
        throw XNotFound("calendar not found in CFileCalendar::CFileCalendar");
    }

    mName=utf32(lQ->ColumnString(1));
    mURI=io::uri(lQ->ColumnString(3));
    mColor=img::CColor((uint32_t)lQ->ColumnInteger(4));

    lQ->Reset();

    io::CFile lFile(mURI);
    io::PStream lStream=lFile.GetStream(io::EMode::READ);

    int lLength=lFile.Size();

    char lData[lLength];

    size_t lRead=lStream->Read((uint8_t*)lData,lLength).Count();

    if(lRead<lLength)
    {
        throw XIO("can't read from stream");
    }

    icalcomponent *lComponent=icalparser_parse_string(lData);

    ParseIcalComponent(lComponent);
}

CFileCalendar::~CFileCalendar()
{
}

img::CColor CFileCalendar::GetColor()
{
    return mColor;
}

CCalendar::EType CFileCalendar::GetType()
{
    return TYPE_FILE;
}

std::wstring CFileCalendar::GetName()
{
    return mName;
}

void CFileCalendar::ParseIcalComponent(icalcomponent *pComponent)
{
    icalcomponent_kind lKind=icalcomponent_isa(pComponent);
    switch(lKind)
    {
    case ICAL_VCALENDAR_COMPONENT:
        ParseVCalendar(pComponent);
        break;
    case ICAL_VEVENT_COMPONENT:
        AddEvent(new CCalendarEvent(this,pComponent));//icalcomponent_new_clone(pComponent)));
        break;
    case ICAL_VTIMEZONE_COMPONENT:
//      AddTimezone(new CCalendarTimezone(icalcomponent_new_clone(pComponent)));
        break;
    default:
        msg_warn() << "unknown component type " <<
                icalcomponent_kind_to_string(lKind) << "\n";
    }
}

void CFileCalendar::ParseVCalendar(icalcomponent *pCal)
{
    for(icalcomponent *lC=icalcomponent_get_first_component(pCal,ICAL_ANY_COMPONENT);
                lC;lC=icalcomponent_get_next_component(pCal,ICAL_ANY_COMPONENT))
    {
        ParseIcalComponent(lC);
    }
}

/*namespace buola*/ } /*namespace bcal*/ }
